import os

class ScriptProcessor:
    def __init__(self, filename, line_creator, is_text = False):
        # 根据是否属于Text，决定不同的处理方式
        self.line_creator = line_creator
        self.xml_indent = 1
        if is_text:
          self.read_lines_from_string(filename)
        else:
          self.input_file = filename
          self.output_file = os.path.splitext(self.input_file)[0] + '_processed.xml'
          self.read_lines()

    def redirect_output(self, filename):
        self.output_file = os.path.splitext(filename)[0] + '_processed.xml'

    def size(self):
        return len(self.lines)

    def get(self, idx):
        if idx < 0 or idx >= len(self.lines):  # 检查上下界
            return None
        return self.lines[idx]

    def read_lines(self):
        with open(self.input_file, 'r', encoding='utf-8') as f:
            self.lines = [self.line_creator(idx, line, self) for idx, line in enumerate(f)]

    def read_lines_from_string(self, text):
        # 将字符串按行分割，并去除每行末尾的换行符
        lines = text.splitlines()
        # 使用列表推导式初始化每一行
        self.lines = [self.line_creator(idx, line, self) for idx, line in enumerate(lines)]

    def process(self):
        # 2. 处理每行内容
        for line in self.lines:
            line.process()

    def save(self):
        with open(self.output_file, 'w', encoding='utf-8') as f_out:
            f_out.write('<?xml version="1.0" encoding="UTF-8"?>\n<Script>\n')
            self.write_to(f_out)
            f_out.write('</Script>')

    def write_to(self, f_out):
        for line in self.lines:
            if not line.is_discard and line.xml:
                f_out.write(" " * (4 * self.xml_indent) + line.xml + '\n')